import React, { Component } from "react";
import styled from "styled-components";
import PubSub from "pubsub-js";

import Header from "./header/header";
import Add from "./comment/add/add";
import List from "./comment/list/list";

class App extends Component {
  // constructor(props) {
  //   super(props);
  //   this.state = {
  //     conments: [
  //       { username: "tom", content: "react香" },
  //       { username: "jack", content: "react真香" },
  //     ],
  //   };
  // }
  // 给组件对象添加state属性,如果有把原来的覆盖,默认是null
  //1.组件对象是this而不是App,App是class
  state = {
    comments: [
      { username: "tom", content: "react香" },
      { username: "jack", content: "react真香" },
    ],
  };
  addComment = (comment) => {
    const { comments } = this.state;
    comments.unshift(comment);
    this.setState({
      comments,
    });
  };
  // 删除指定评论
  // deleteComment = (msg = "", index) => {
  deleteComment = (index) => {
    const { comments } = this.state;
    //1.增删改都可以做
    comments.splice(index, 1);
    //2.add加,不删
    // comments.splice(index, 0,{});
    //3.替换一个
    // comments.splice(index, 1,{});
    this.setState({
      comments,
    });
  };
  componentDidMount() {
    PubSub.subscribe("deleteComment", (msg, index) => {
      this.deleteComment(index);
    });
    //如果pubsub设计的第一个参数是data的话,我们被调用函数只接收一个参数就可以这么写了
    // PubSub.subscribe("deleteComment", this.deleteComment(index));
    // PubSub.subscribe("deleteComment", this.deleteComment);
  }
  render() {
    const { comments } = this.state;
    return (
      <Wrapper>
        <Header />
        <div className="container">
          <div className="row" style={{ marginTop: "5%" }}>
            <div className="col-xs-12 col-sm-6 col-md-6 col-lg-6">
              <Add addComment={this.addComment} />
            </div>
            <div
              className="col-xs-12 col-sm-6 col-md-6 col-lg-6"
              style={{ marginTop: "2%" }}
            >
              <List comments={comments} deleteComment={this.deleteComment} />
            </div>
          </div>
        </div>
      </Wrapper>
    );
  }
}
const Wrapper = styled.div`
  width: 100%;
  height: 100%;
`;

export default App;
